package day6

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

var numRandom int
var lock sync.Mutex
var rwMutex sync.RWMutex
var wg sync.WaitGroup

func read(i int) {
	rwMutex.RLock()
	time.Sleep(time.Duration(rand.Intn(i)) * time.Second)
	fmt.Println("执行读操作 num = ", numRandom)
	rwMutex.RUnlock()
	wg.Done()
}

func write(i int) {
	rwMutex.Lock()
	numRandom = rand.Intn(100)

	time.Sleep(time.Duration(rand.Intn(i)) * time.Second)
	fmt.Println("执行写操作 num = ", numRandom)
	rwMutex.Unlock()
	wg.Done()
}

func Test_lock() {
	wg.Add(6)
	for i := 1; i < 4; i++ {
		go write(i)
	}

	for i := 1; i < 4; i++ {
		go read(i)
	}

	wg.Wait()

}
